

	window.para = {
		TRACK:'utm_source=EDM&utm_medium=',
		rev : '',
		domain:'',
		number:1,
		date:20171021,
		tmp : $("<div id='model'></div>"),
		html:null,
		meSystem:['fashionme','berrylook','stylishplus','orderplus','calladream'],
		outherA:['aqilabuy','bellalike','lululike'],
		api:{ //下标参数 1.当前模板追踪 2.请求接口 3.图片资源阿里云前缀 4.当前币种符号
			'bellalike':['BL','http://14.18.205.131:1000/api/product/edm?pid=46&spus='],
			'bellalike-spain':['BL','https://shop.bellalike.com/admin/index.php?route=api/product/infoapi&lan=MXN&goods_sn=','',true],
			'luvyle':['LV','https://www.luvyle.com/admin/index.php?route=api/product/infoapi&goods_sn='],
			'sugarmod':['SUMO','https://www.sugarmod.com/admin/index.php?route=api/product/infoapi&goods_sn='],
			'hellocloth':['HECL','https://www.hellocloth.com/admin/index.php?route=api/product/infoapi&goods_sn='],

			'fashionme':['FME','https://websolr.fashionme.com/dla?insku=','fm.'],
			'berrylook':['BERRY','https://websolr.berrylook.com/dla?insku=','bl.'],
		 	'calladream': ['CDR', 'https://websolr.calladream.com/dla?insku=', 'cd.'],
			'stylishplus':['STPL','https://websolr.stylishplus.com/dla?site=100&insku=','sp.'],
			'orderplus':['ORPL','https://websolr.stylishplus.com/dla?site=17&insku=',''],

			'aqilabuy':['AQB','http://14.18.205.131:1000/api/product/edm?pid=6&spus=',''],
			'lululike':['LLK','http://14.18.205.131:1000/api/product/edm?pid=9&spus=','']
		},
		banner:null,
		banner2:null,
		dress:null,
		hot:null,
		list:[]
	};


	inEvent();

	function inEvent(){

		//初始化local里的数据
		initData();
		//初始化组件
		$('#selectRev').comSelect({init:1});
		//保存
		$('#save').on('click',function(){
			result(1)
		});
		//重置
		$('#reset').on('click',function(){
			localStorage.removeItem('templateDataA');
		});
		//上传事件
		$("input[type='file']").on('change',function(){
			up($(this)[0],$(this).attr('data-name'))
		});

		//选择模板事件
		$("input[name='template']").on('change',function(){

			para.rev = $(this).val();
			//根据模板选择list跳转路径
			if(para.meSystem.indexOf(para.rev) >= 0){
				para.domain = 'https://www.' + para.rev.replace(/([a-zA-Z]+)-*.*/,'$1') + '.com/en/Products/';
			}else{
				para.domain = 'https://www.' + para.rev.replace(/([a-zA-Z]+)-*.*/,'$1') + '.com/';
			}
			//拼接追踪
			para.api[para.rev][0] = para.TRACK + para.api[para.rev][0];

			para.tmp.load('template/'+para.rev+'.html?'+new Date().getTime()+' #M',function(res,status){
				if(status == 'success'){
					var str = res;
					para.html = str.replace(/<table\s+id[\s\S]+<\/html>/g,'');
					$.comMessage({
						type:'success',
						text:para.rev + '模板载入完成',
						time:2500
					})
				}
			})
		});

		//生成
		$('#start').on('click',function(){
			//执行基本校验
			if(!$("input[name='template']").val()){
				$.comMessage({
					type:'warning',
					text:'请选择模板！',
					time:2500
				});
				return;
			}
			//para赋值
			result();

			if(para.list.length>0){
				request(para.list);
			}else{
				renderAll();
			}
			//请求SKU
			//renderBanner();
			//dateReplace();
		});
	}


	//请求所有SKU数据列表
	function request(arr){
		var num = 0;
		var errBox = [];
		var noBox = {};
		var arrObj = [];

		//var isTrue = new RegExp(para.rev,"g").test(para.outherA);
		var isTrue = para.outherA.indexOf(para.rev) >= 0;

		arr.forEach(function(item,index){
			$.ajax({
				type:'get',
				url:para.api[para.rev][1] + item,
				data:'',
				dataType:isTrue ? 'json': 'jsonp',
				jsonp:isTrue ? false:'jsonpcallback',
				beforeSend:function(req){
					isTrue ? req.setRequestHeader('pms-token','orderplus') : '';
					$('#start').prop('disabled',true)
				},
				success:function(data){
					var obj = null;
					if(typeof data == 'string'){data = JSON.parse(data)}
					if(para.meSystem.indexOf(para.rev) >= 0){
						obj = data.response.data[0]
					}else if(isTrue){
						obj = data.response[0];
					}else{
						obj = data.data
					}
					if(!obj){
						noBox[index] = true;
					}else{
						arrObj[index] = obj;
					}
				},
				error:function(xhr,err,msg){
					errBox.push(item);
					noBox[index] = true;
				},
				complete:function(){
					num++;
					if(num>=arr.length){
						/*if(errBox.length>0){
							$.alert('sku请求失败'+errBox.length+'个!',function(){
								console.log(errBox);
							})
						}else{*/
							if(Object.keys(noBox).length>0){
								$.alert('sku'+Object.keys(noBox).length+'条没有数据是否继续?',function(){
									renderAll(arrObj);
									//重置页面sku覆盖
									var resetList = para.list.filter(function(item,index){
										if(!noBox[index]){
											return item;
										}
									});
									para.list = resetList;
									$("textarea[name='sku']").val(resetList.join(','));
								})
							}else{
								renderAll(arrObj)
							}
						//}
						$('#start').prop('disabled',false)
					}
				}
			})
		})
	}
	function renderAll(temp){
		if(temp){
			var newData = dataStructure(temp);
				renderList(newData);
		}
		renderBanner();
		dateReplace();
		para.html = para.html + para.tmp.html() + "</body></html>";
		para.html = para.html.replace(/&amp;/g,'&');
		$.comMessage({
			type:'prompt',
			text:'模板渲染完成！',
			time:2500
		});
		saveHtml();
	}

	//渲染banner/view
	function renderBanner(){
		var navBanner = para.tmp.find("[data-name='banner']");
		var dress = para.tmp.find("[data-name='dress']");
		var hot = para.tmp.find("[data-name='hot']");
		var navBanner2 = para.tmp.find("[data-name='banner2']");
		//banner
		var blink = para.banner.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0]:'?'+para.api[para.rev][0];

		navBanner.find('a').prop('href',para.banner.link+blink+para.date+'&utm_campaign=Link508');
		navBanner.find('img').prop({
			//'src': link + "banner1.jpg",
			'src': para.banner.src,
			'title':para.banner.title
		});
		//view-more
		para.tmp.find("[data-name='more']").prop('href',para.banner.link+blink+para.date+'&utm_campaign=Link509');

		//bannerDress
		var b2link = para.dress.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
		dress.prop('href',para.dress.link+b2link+para.date+'&utm_campaign=Link600');
		dress.find('img').prop({
			//'src': link + "banner2.jpg",
			'src':para.dress.src,
			'title':para.dress.title
		});

		//bannerHot
		var b3link = para.hot.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
		hot.prop('href',para.hot.link+b3link+para.date+'&utm_campaign=Link601');
		hot.find('img').prop({
			//'src': link + "banner3.jpg",
			'src':para.hot.src,
			'title':para.hot.title
		});

		//banner2
		var b4link = para.banner2.link.indexOf('?')>=0 ? '&'+para.api[para.rev][0] : '?'+para.api[para.rev][0];
		navBanner2.find('a').prop('href',para.banner2.link+b4link+para.date+'&utm_campaign=Link508');
		navBanner2.find('img').prop({
			//'src': link + "banner1.jpg",
			'src': para.banner2.src,
			'title':para.banner2.title
		});

		//隐藏显示
		if(!para.dress.src||!para.hot.src){para.tmp.find(".dress-hot").hide();}
		if(!para.banner2.src){navBanner2.hide();}
	}

	//渲染链接
	function dateReplace(){
		para.tmp.find('.d').each(function(index,item){
			var str = $(item).prop('href');
			if(/utm_source/.test(str)){
				var link = str.replace(/utm_source.+[A-Z]+\d+/,para.api[para.rev][0] + para.date);
				$(item).prop('href',link);
			}
		})
	}

	//数据结构处理
	function dataStructure(res){
		var arr = [];
		/*{goods_name:'',url:'',img:'',price:'',market_price:''};*/
		$.each(res,function(index,item){
			if(!item){
				return true;
			}
			var tmpUrl = '';
			var obj = {};
			/**
			 ** me系统
			 **/
			if(para.meSystem.indexOf(para.rev) >= 0){
				//名称
				obj.goods_name = item.goods_name;
				//链接
				tmpUrl = item.goods_name.replace(/^\s+/,'').replace(/\s{2,}/g,' ').replace(/\&*/g,'');
				obj.url = para.domain + tmpUrl.toLowerCase().split(' ').join('-') + '-' + item.id + '.html?';
				//图片
				var sizePara = (para.rev == 'calladream') ? "@!h250-w250" : "@!h400-w300";
				obj.img = "http://"+para.api[para.rev][2]+"aopcdn.com/" + item.main_original_img_path.replace(/^images/,'goods') + sizePara;
			/**
			 ** AQB
			 **/
			}else if(para.outherA.indexOf(para.rev) >= 0){
				obj.goods_name = item.name;
				obj.url = item.link + '?';
				obj.url = obj.url.replace(new RegExp("(^http.+com)*"),'https://www.' + para.rev + ".com");
				obj.img = item.img;
			/**
			 ** open
			 **/
			}else{
				//名称
				obj.goods_name = item.goods_name;
				//链接
				tmpUrl = item.goods_name.replace(/^\s+/,'').replace(/\s{2,}/g,' ');
				obj.url = para.domain + tmpUrl.toLowerCase().split(' ').join('-') + '-p-' + item.goods_id  + '.html?';
				//图片
				obj.img = item.thumb_pic_detail[0].img_path;
			}

			//价格
			obj.price = para.api[para.rev][3] ? item.price : '$' + item.price.toFixed(2);
			//划线价
			if(item.market_price){
				obj.market_price = para.api[para.rev][3] ? item.market_price : '$' + item.market_price.toFixed(2);
			}

			arr.push(obj);
		});
		return arr;
	}

	//渲染列表
	function renderList(data){
		var str = '';
		var arrDom = [];
		var modelA = para.tmp.find("#modelA").clone();

		data.forEach(function(item,index){
			if(!item){
				$.comMessage({
					type:'prompt',
					text:'sku不存在！',
					time:2500
				});
				return;
			}
			modelA.find("[data-name='link']").prop({
				'href':item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number,
				'title':para.api[para.rev][3] ? item.title_en : item.goods_name
			});
			para.number++;
			modelA.find("[data-name='link2']")
					.prop('href',item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number);
			para.number++;

			//如果有描述
			if(modelA.find("[data-name='link3']").length){
				modelA.find("[data-name='link3']").prop({
					'href':item.url+para.api[para.rev][0]+para.date+'&utm_campaign=Link' + para.number,
					'title':para.api[para.rev][3] ? item.title_en : item.goods_name
				}).html(para.api[para.rev][3] ? item.title_en : item.goods_name);
				para.number++;
			}

			//如果有划线价则添加否则清除划线价
			if(modelA.find("[data-name='market_price']").length && item.market_price){
			  	modelA.find("[data-name='market_price']").html(item.market_price);
			}else{
				modelA.find("[data-name='market_price']").html("");
			}
			modelA.find("[data-name='img']").prop('src',item.img);
			modelA.find("[data-name='price']").html( item.price );
			arrDom.push(modelA.children('tr').html())
		});

		//console.log(arrDom)
		arrDom.forEach(function(item,index){
			if(index%3 == 0){
				item = "<tr>" + item
			}else if(index%3 == 2){
				item = item + "</tr>"
			}
			str+=item;
		});

		para.tmp.find("#tbody").append(str);
	}

	//para赋值操作
	function result(type){

		var date = $("input[name='date']").val();
		var banner = {
			link : $("input[name='b1link']").val(),
			src : $("input[name='b1src']").val(),
			title : $("input[name='b1title']").val()
		};
		var banner2 = {
			link : $("input[name='b4link']").val(),
			src : $("input[name='b4src']").val(),
			title : $("input[name='b4title']").val()
		};
		var dress = {
			link : $("input[name='b2link']").val(),
			src : $("input[name='b2src']").val(),
			title : $("input[name='b2title']").val()
		};
		var hot = {
			link : $("input[name='b3link']").val(),
			src : $("input[name='b3src']").val(),
			title : $("input[name='b3title']").val()
		};
		var list = $("textarea[name='sku']").val().replace(/\s/g,'');

		if(!type){
			para.date = date;
			para.banner = banner;
			para.banner2 = banner2;
			para.dress = dress;
			para.hot = hot;
			para.list = list ? list.split(',') : [];
		}else{
			/*localStorage.date = date;
			localStorage.banner = JSON.stringify(banner);
			localStorage.banner2 = JSON.stringify(banner2);
			localStorage.dress = JSON.stringify(dress);
			localStorage.hot = JSON.stringify(hot);
			localStorage.list = list;*/

			var jsonData = {
				date:date,
				banner:banner,
				banner2:banner2,
				dress:dress,
				hot:hot,
				list:list
			};
			localStorage.templateDataA = JSON.stringify(jsonData);
		}
	}

	//初始化local里的数据
	function initData(){
		var jsonData = localStorage.templateDataA ? JSON.parse(localStorage.templateDataA) : {};

		var banner = jsonData.banner ? jsonData.banner : {};
		var banner2 = jsonData.banner2 ? jsonData.banner2 : {};
		var dress = jsonData.dress ? jsonData.dress : {};
		var hot = jsonData.hot ? jsonData.hot : {};

		$("input[name='date']").val(jsonData.date);
		$("textarea[name='sku']").val(jsonData.list);

		$("input[name='b1link']").val(banner.link);
		$("input[name='b1src']").val(banner.src);
		$("input[name='b1title']").val(banner.title);

		$("input[name='b4link']").val(banner2.link);
		$("input[name='b4src']").val(banner2.src);
		$("input[name='b4title']").val(banner2.title);

		$("input[name='b2link']").val(dress.link);
		$("input[name='b2src']").val(dress.src);
		$("input[name='b2title']").val(dress.title);

		$("input[name='b3link']").val(hot.link);
		$("input[name='b3src']").val(hot.src);
		$("input[name='b3title']").val(hot.title);

		/*var banner = localStorage.banner ? JSON.parse(localStorage.banner) : '';
		var banner2 = localStorage.banner2 ? JSON.parse(localStorage.banner2) : '';
		var dress = localStorage.dress ? JSON.parse(localStorage.dress) : '';
		var hot = localStorage.hot ? JSON.parse(localStorage.hot) : '';*/

		/*$("input[name='date']").val(localStorage.date);
		$("textarea[name='sku']").val(localStorage.list);

		$("input[name='b1link']").val(typeof banner.link == 'function' ? '' : banner.link);
		$("input[name='b1src']").val(banner.src);
		$("input[name='b1title']").val(banner.title);

		$("input[name='b4link']").val(typeof banner2.link == 'function' ? '' : banner2.link);
		$("input[name='b4src']").val(banner2.src);
		$("input[name='b4title']").val(banner2.title);

		$("input[name='b2link']").val(typeof dress.link == 'function' ? '' : dress.link);
		$("input[name='b2src']").val(dress.src);
		$("input[name='b2title']").val(dress.title);

		$("input[name='b3link']").val(typeof hot.link == 'function' ? '' : hot.link);
		$("input[name='b3src']").val(hot.src);
		$("input[name='b3title']").val(hot.title);*/
	}

	//图片上传
	function up(inputObj,name){
		var fd = new FormData();
		fd.append('file',inputObj.files[0]);
		fd.append("site_name",para.rev);
		$.ajax({
			type : 'post',
			url : 'http://admin.fashionmia.com/opbm.php?a=EdmImages&m=Api',
			data : fd,
			cache : false,
			dataType:'json',
			processData : false,
			contentType : false,
			success : function(data){
				if(data.status == 0){
					//debugger;
					$("input[name='"+name+"']").val(data.data.img);
				}
			},
			error : function(){
				$.comMessage({
					type:'warning',
					text:'图片上传失败！',
					time:2500
				});
			}
		})
	}

	//保存html
	function saveHtml(){
		$.ajax({
			type : 'post',
			url : 'http://admin.fashionmia.com/opbm.php?a=EdmHtml&m=Api',
			data:{
				html:para.html,
				site_name:para.rev
			},
			success:function(res){
				var data = JSON.parse(res);
				if(data.status == 0){
					$("input[name='callback']").val(data.data.img);
					$.comMessage({
						type:'prompt',
						text:'链接已生成！',
						time:2500
					});
				}
			},
			error : function(){
				$.comMessage({
					type:'prompt',
					text:'模板保存失败！',
					time:2500
				});
			},
			complete:function(){
				$('#start').prop('disabled',false)
			}
		})
	}
